Skip to content

Hw 1#1

Open
BorisKoz wants to merge 60 commits intomasterfrom
HW-1
Open

Hw 1#1
BorisKoz wants to merge 60 commits intomasterfrom
HW-1

Conversation

@BorisKoz
Copy link
Copy Markdown
Owner

@BorisKoz BorisKoz commented Mar 11, 2021

1й пул на дз

@IlyaSaneev
Copy link
Copy Markdown
Collaborator

CI должен проходить успешно для допуска к проверке.

@IlyaSaneev IlyaSaneev assigned BorisKoz and unassigned IlyaSaneev Mar 14, 2021

// open database file. check if not null.
int open_car_database(FILE** db_ptr, const char* basename) {
*db_ptr = fopen(basename, "r+");
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если в db_ptr прилетит NULL, программа упадет. Это относится и к другим функциям, везде нужно проверять валидность переданных указателей.

return_code = ALLOCATE_ERROR;
}
if (return_code !=0)
break;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Большое количество break, постарайся соблюдать правила структурного программирования и делать код более линейным.

car* input_car = (car*)malloc(sizeof(car));
car* found_car = (car*)malloc(sizeof(car));

FILE* db = NULL, * search = NULL;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вкусовщина, но лучше не объявлять переменные одного типа в строку, делает код менее читаемым

return 0;
}

int allocate_string(char** string_in_car, const char buffer_value[SIZE_BUF]) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне кажется, buffer_value лучше передать так: const char buffer_value*

int error_out(int err_code) {
switch (err_code) {
case 1:
printf("%s", "NULL POINTER!");
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ошибки лучше писать в поток ошибок


TEST(open_car_database, ok) {
FILE* pointer;
EXPECT_EQ(open_car_database(&pointer, "../../db.txt"), 0);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Плохо, что тесты зависят от внешних файлов, не создаваемых в тестах

return INCORRECT_ENTRY;
}
}
if (strtof(read_buffer[0], NULL) > 0 && strtof(read_buffer[1], NULL) > 0
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше сложить результат работы функции в переменные, чтоб не делать лишнюю работу

Comment on lines +19 to +21
file(GLOB sources
"${PROJECT_SOURCE_DIR}/include/*.h"
"${PROJECT_SOURCE_DIR}/src/*.c")
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стоит явно указывать все единицы трансляции (*.c) для исполняемого файла, хидера указывать не нужно

@@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.15)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет продуктовой цели, только тестовая.

Comment on lines +14 to +15
#include <stdio.h>
#include <stdlib.h>
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хидера стоит располагать в начале файла.

return 0;
}

int allocate_string(char** string_in_car, const char buffer_value[SIZE_BUF]) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Судя по реализации задача метода скопировать строку в другую память. Название метода не соответствует назначению.
Рассмотри
https://man7.org/linux/man-pages/man3/strdup.3.html#:~:text=The%20strdup()%20function%20returns,copies%20at%20most%20n%20bytes.

Либо создай свой аналог с аналогичной сигнатурй char *strdup(const char *s);

Comment on lines +31 to +44
int open_car_database(FILE** db_ptr, const char* basename);
int read_car_instance(FILE* db_ptr, car *car_read);
int print_car_instance(const car* car_print);
float comparison(const car* car_1, const car* car_2);
int free_car(car* car_1);
int copy_car(car* dest, car* src);
int search_in_base(car* input_car, car* found_car, FILE* db);

int allocate_string(char** string_in_car, const char buffer_value[SIZE_BUF]);
int min_of_3(int i, int i1, int i2);
int car_nullptr(car* car_1);
float string_distance(const char* a, const char* b);
float distance_fl(float a, float b);
int error_out(int err_code);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В .h стоит выносит только те методы, который нужны вызывающей программе для работы с машинами, остальные методы стоит держать только в .c. Принципы инкапсуляции применимы и к с.

Comment on lines +167 to +171
int car_nullptr(car* car_1) {
car_1->body_type = NULL;
car_1->model_name = NULL;
return 0;
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не нужен, занулять память можно при создании объекта, например через calloc, или явно memset после malloc

// open fault check
if (open_car_database(&db, argv[1]) != 0 ||
open_car_database(&search, argv[2]) != 0) {
return_code = ALLOCATE_ERROR;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

сразу break/return

break;

// write to file for search
char read_buffer[SIZE_BUF];
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

= {} // zero init


// write to file for search
char read_buffer[SIZE_BUF];
for (int i = 0; i < 5; i++) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что такое 5? Введи константу или дефайн

Comment on lines +35 to +41
if (scanf(SCAN_FORMAT , read_buffer) != 1) {
return_code = INCORRECT_ENTRY;
} else {
fputs(read_buffer, search);
if (i < 4)
fputs(" ", search);
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Форматирование кода!

@BorisKoz BorisKoz assigned IlyaSaneev and unassigned BorisKoz Mar 16, 2021
@BorisKoz BorisKoz requested a review from IlyaSaneev March 16, 2021 17:50
Comment on lines +24 to +28
for (int i = 0; i < 5; i++) {
if (fscanf(db_ptr, SCAN_FORMAT, read_buffer[i]) != 1) {
return INCORRECT_ENTRY;
}
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Избавься от литералов в коде, что такое 5?

Comment on lines +29 to +31
car_read->engine_power = strtof(read_buffer[0], NULL);
car_read->maximum_velocity = strtof(read_buffer[1], NULL);
car_read->fuel_consumption = strtof(read_buffer[2], NULL);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если в каждом индексе лежит конкретная характеристика, то индексам лучше дать имена

Comment on lines +71 to +73
float string_distance(const char* a, const char* b) {
size_t x = 0, y = 0, len_a = strlen(a), len_b = strlen(b);
int matrix[SIZE_BUF + 1][SIZE_BUF + 1];
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что если залетит null?

Comment on lines +148 to +159
case 1:
fprintf(stderr, "%s", "NULL POINTER!\n");
return 1;
case 2:
fprintf(stderr, "%s", "INCORRECT INPUT\n");
return 2;
case 3:
fprintf(stderr, "%s", "ALLOCATION FAULT\n");
return 3;
case 4:
fprintf(stderr, "%s", "INCORRECT OUTPUT\n");
return 4;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ошибкам нужно дать имена

// Copyright 2021 <BKZ>
#include <stdio.h>
#include <stdbool.h>
#include "../include/cars.h"
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Такого пути быть не должно, подключи директорию в cmake через include_directories

Comment on lines +13 to +28
TEST(min, ok) {
ASSERT_EQ(min_of_3(1, 2, 3), 1);
ASSERT_EQ(min_of_3(1, 3, 2), 1);
ASSERT_EQ(min_of_3(2, 1, 3), 1);
ASSERT_EQ(min_of_3(3, 1, 2), 1);
ASSERT_EQ(min_of_3(2, 3, 1), 1);
ASSERT_EQ(min_of_3(3, 2, 1), 1);
}
TEST(Levenstein, ok) {
EXPECT_EQ(string_distance("Toyota", "Toyota"), 1);
EXPECT_EQ(string_distance("Toyota", "Toy"), 0.5);
EXPECT_EQ(string_distance("Toyota", "Renaul"), 0);
}
TEST(distance, ok) {
EXPECT_EQ(distance_fl(1, 2), 0.5);
EXPECT_EQ(distance_fl(4, 1), 0.25);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В названии теста должно быть его описание. первое слово - тестируемая функция(группа тестов), второе - то, что конкретно тест проверяет

@BorisKoz
Copy link
Copy Markdown
Owner Author

выкатил фикс

@BorisKoz BorisKoz assigned IlyaSaneev and unassigned IlyaSaneev Mar 18, 2021
@IlyaSaneev IlyaSaneev removed their assignment Mar 20, 2021
@IlyaSaneev
Copy link
Copy Markdown
Collaborator

зачет

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants